/**
 * @description 本地存储辅助函数
 */

import {isNull, isUndefined, each, eachRight, now} from 'lodash';
// import json from 'json';
const isNone = (value: any) => (isNull(value) || isUndefined(value));


// 本地存储的key
const STORAGE_KEY = encodeURI('_dv_storage_');

/**
 * 临时存储的变量
 * @type {Object}
 */
let storageValue = {};
try {
  const value = localStorage.getItem(STORAGE_KEY)
  storageValue = typeof value === 'string' ? JSON.parse(value) : {};
} catch (e) {
  storageValue = {};
}
/**
 * 更新localStorage
 */
const update = () => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(storageValue));
};

/**
 * 判断是否已过期
 * @param expire
 * @returns {boolean}
 */
const isExpired = (expire: number) => !isNone(expire) && expire !== 0 && expire - now() < 0;

/**
 * 存储本地数据
 * @param {string} key 数据名
 * @param {*} value 值
 * @param {number|Date} [expire] 过期时间,不传或0,表示永不过期
 * @return {boolean}
 */
export const setStorage = (key: string, value: string, expire?: any) => {
  // 值不是null(是null没意义,浪费空间),并且没有过期
  if (!isNone(value) && !isExpired(expire)) {
    storageValue[key] = {
      value,
      expire, // 设置过期时间
    };

    update();
    return true;
  }

  return false;
};

/**
 * 获取本地数据
 * @param {string} key 数据名
 * @returns {*}
 */
export const getStorage = (key: string) => {

  const storage = storageValue[key];

  if (!isNone(storage) && !isExpired(storage.expire)) {

    return isNone(storage.value) ? null : storage.value;
  }

  return null;
};

/**
 * 给localStorage续期
 * @param {string} key 数据名
 * @param {number|Date} expTime 过期时间
 */
export const keepStorage = (key: string, expTime: number) => setStorage(key, getStorage(key), expTime);

export const isItemExpire = (key: string) => {
  // 不存在肯定过期
  return !storageValue[key] && isExpired(storageValue[key].expire);
};

/**
 * 删除本地数据
 * @param {string} key 数据名
 * @return {boolean}
 */
export const removeStorage = (key: string) => {

  const storage = getStorage(key);

  if (storage) {

    delete storageValue[key];

    update();
  }

  return true;
};

/**
 * 清空本地数据
 */
export const clearStorage = () => {
  eachRight(storageValue, removeStorage);
};

// 每次打开页面时, 清空一次过期的数据
each(storageValue, (storage: any, key: string) => {
  if (isExpired(storage.expire)) {
    delete storageValue[key];
  }
});


update();
